import React, { Component } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import qs from 'qs';
import _ from 'lodash';
import moment from 'moment';

import { Form } from '@ant-design/compatible';
import PageHearder from '@/components/PageHeader';
import { addTab, timeLimit } from '@/utils/utils';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import {
  Card,
  Row,
  Col,
  DatePicker,
  Input,
  Button,
  Table,
  Modal,
  message,
} from 'antd';
import { CheckCircleFilled } from '@ant-design/icons';

import '@ant-design/compatible/assets/index.css';

const { RangePicker } = DatePicker;
const { Item } = Form;
const { confirm } = Modal;
const { pathname } = window.location;

interface consumeDetailProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  courierRecharge: any;
  loading:boolean;
  dataList:any;
}

interface consumeDetailState {
  searchValues: any;
  pageIndex:any;
  pageSize:any;
}

@connect(({
  consumeDetail: { dataList },
  loading,
}: any) => ({
  dataList,
  loading: loading.effects['consumeDetail/fetch'],
}))

class consumeDetailElem extends Component<consumeDetailProps, consumeDetailState> {
  columns = [
    {
      title: '消费账户',
      dataIndex: 'phone',
    },
    {
      title: '操作类型',
      dataIndex: 'typeName',
      render: (text: string) => (text || '--'),
    },
    {
      title: '消费方式',
      dataIndex: 'subTypeName',
      render: (text: string) => (text || '--'),
    },
    {
      title: '消费金额(元)',
      dataIndex: 'amountTxt',
    },
    {
      title: '投递主账户余额(元)',
      dataIndex: 'toMainTxt',
    },
    {
      title: '投递副账户余额(元)',
      dataIndex: 'toDeputyTxt',
    },
    {
      title: '消费时间',
      dataIndex: 'createTime',
      width: 200,
    },
  ];

  state: consumeDetailState = {
    searchValues: {},
    pageIndex: 1,
    pageSize: 20,
  };

  componentDidMount() {
    this.setFieldsValue();

    const { searchValues: { phone, startTime } } = this.state;
    if (phone && startTime) this.fetchDataValues();
  }

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...searchValues } = query;
    return {
      searchValues,
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || 20,
    };
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageIndex, pageSize } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
     || pageIndex !== prevState.pageIndex
     || pageSize !== prevState.pageSize) {
      this.setFieldsValue();

      const { phone, startTime } = searchValues;
      if (phone && startTime) this.fetchDataValues();
    }
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({ type: 'consumeDetail/clear' });
  }

  // 查询列表
  fetchDataValues = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'consumeDetail/fetch',
      payload: this.getQueryParams(),
    });
  };

  setFieldsValue = () => {
    // 设置表单
    const { searchValues: { startTime, endTime, ...others } } = this.state;

    if (startTime) {
      others.start_end_time = [moment(startTime), endTime ? moment(endTime) : ''];
    } else {
      others.start_end_time = [
        moment(moment().subtract(3, 'month').format('YYYY-MM-DD 00:00:00')),
      ];
    }

    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(others);
  };

  // 查询
  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, fieldsValue) => {
      if (errors) return;

      const { start_end_time = [], phone } = fieldsValue;

      if (!start_end_time) {
        message.error('请选择起止时间');
        return;
      }

      if (!start_end_time[0]) {
        message.error('请选择开始时间');
        return;
      }

      if (!phone) {
        message.error('请选择快递员手机号');
        return;
      }

      fieldsValue.startTime = start_end_time[0]
        ? moment(start_end_time[0]).format('YYYY-MM-DD HH:mm:ss')
        : moment().subtract(3, 'month').format('YYYY-MM-DD 00:00:00');

      fieldsValue.endTime = start_end_time[1] && moment(start_end_time[1]).format('YYYY-MM-DD HH:mm:ss');

      delete fieldsValue.start_end_time;

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '快递员消费明细',
        url: `${pathname}?${qs.stringify(fieldsValue)}`,
        isTopMenu: true,
      });
    });
  };

  // 重置
  handleFormReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '快递员消费明细',
      url: pathname,
      isTopMenu: true,
    });

    dispatch({ type: 'consumeDetail/clear' });
  };

  // 获取参数
  getQueryParams = () => {
    const { searchValues, pageIndex, pageSize } = this.state;
    const params = { ...searchValues, pageIndex, pageSize };
    return params;
  };

  // 导出
  exportExel = () => {
    const { form: { getFieldsValue } } = this.props;
    const { phone } = getFieldsValue(['phone']);
    const reg = /^1[3456789]\d{9}$/;
    const _this = this;

    if (reg.test(phone)) {
      confirm({
        title: `确认导出【${phone}】的消费明细`,
        icon: <CheckCircleFilled style={{ color: '#52c41a' }} />,
        onOk() {
          const { dispatch } = _this.props;
          dispatch({
            type: 'consumeDetail/export',
            payload: _this.getQueryParams(),
          });
        },
      });
    } else {
      message.error('请填写正确的快递员手机号！');
    }
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, pageIndex, pageSize };
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '快递员消费明细',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  render() {
    const {
      form: { getFieldDecorator },
      dataList,
      loading,
    } = this.props;

    const {
      pageIndex,
      pageSize,
    } = this.state;

    const dataSource = dataList ? dataList.list : [];
    const pagination: object = {
      total: dataList ? dataList.count : 0,
      current: pageIndex,
      pageSize,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showTotal: () => `共${dataList.count || 0}条数据`,
      onChange: this.onSelectChange,
      onShowSizeChange: this.onSelectChange,
    };

    return (
      <>
        <PageHearder />

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={26}>
              <Col md={10} sm={24}>
                <Item label="　起止时间" colon={false}>
                  {getFieldDecorator('start_end_time', {
                    initialValue: [
                      moment(
                        moment().subtract(3, 'month').format('YYYY-MM-DD 00:00:00'),
                      ),
                      '',
                    ],
                  })(
                    <RangePicker
                      showTime
                      placeholder={['开始时间', '截止时间']}
                      style={{ width: '100%' }}
                      format="YYYY/MM/DD HH:mm:ss"
                      disabledDate={current => timeLimit(current, 36)}
                      ranges={{
                        今天: [moment().startOf('day'), moment().endOf('day')],
                        本周: [moment().startOf('week'), moment().endOf('week')],
                        本月: [moment().startOf('month'), moment().endOf('month')],
                        上月: [
                          moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
                          moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
                        ],
                      }}
                    />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="快递员手机号" colon={false}>
                  {getFieldDecorator('phone')(
                    <Input
                      allowClear
                      autoComplete="off"
                      placeholder="请输入"
                      style={{ width: '100%' }}
                    />,
                  )}
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    type="primary"
                    className="addButton marginL16 smallButton"
                    onClick={this.handleFormReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton"
              onClick={this.exportExel}
            >
              导出
            </Button>
          </div>
          <Table
            rowKey="orderId"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 1400 }}
          />
        </Card>
      </>
    );
  }
}

export default Form.create<consumeDetailProps>()(consumeDetailElem);
